/**
 *
 */
package com.uaroadshow.webpay.web.controller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.wechat.entity.pay.PayTransaction;
import com.demo2do.core.wechat.entity.response.Response;
import com.uaroadshow.webpay.entity.PaymentContext;
import com.uaroadshow.webpay.entity.callback.CallbackRequest;
import com.uaroadshow.webpay.entity.callback.CallbackResponse;
import com.uaroadshow.webpay.entity.callback.WeapppayCallbackRequest;
import com.uaroadshow.webpay.entity.callback.WechatpayCallbackRequest;
import com.uaroadshow.webpay.handler.PaymentFacade;
import com.uaroadshow.webpay.service.PaymentService;

/**
 * @author downpour
 *
 */
@Controller
@RequestMapping("")
public class PaymentCallbackListener {

    private static final Logger logger = LoggerFactory.getLogger(PaymentCallbackListener.class);

    @Autowired
    private PaymentFacade paymentFacade;

    @Autowired
    private PaymentService paymentService;
    
    /**
     * 
     * @param requestParameters
     * @return
     */
    @RequestMapping(value = "/wechatpay-callback", method = RequestMethod.POST, produces = "application/xml; charset=UTF-8")
    public @ResponseBody Response onWechatpayNotify(@RequestBody Map<String, String> requestParameters) {
    	
    	CallbackRequest callbackRequest = new WechatpayCallbackRequest(requestParameters);
        
    	CallbackResponse callbackResponse = new CallbackResponse();
    	
    	try {

    	    if(callbackRequest.isValid()) {
    	        
    	        // 0. extract pay_transaction from request
    	        PayTransaction payTransaction = callbackRequest.getPayTransaction();
    	        
    	        // 1. load payment_context by out_trade_no
                PaymentContext paymentContext =  paymentService.loadContext(payTransaction.getOutTradeNo());
                
                // 2. validate payment_context and callback_request, may throw business exception here
                paymentFacade.validate(paymentContext, callbackRequest);
                
                // 3. do paid process 
                callbackResponse = paymentFacade.paid(paymentContext, payTransaction);
    	        
    	    } else {
    	        
    	        callbackResponse.fail().message("支付参数有误");
    	        
    	    }
    	    
    	} catch (BusinessException e) {
    	    
    	    logger.error("#onWechatpayNotify - An business error occurs when doing callback process.", e);
    	    
    	    callbackResponse.fail().message(e.getMessage());
    	    
    	} catch (Exception e) {
    	    
    	    logger.error("@onWechatpayNotify - An exception error occurs when doing callback process.", e);
    	    
    	    callbackResponse.fail().message("支付回调失败");
    	}

        return callbackResponse.isValid() ? Response.newInstance().success() : Response.newInstance().fail(callbackResponse.getMessage());
    
    }
    
    /**
     * 
     * @param requestParameters
     * @return
     */
    @RequestMapping(value = "/weapppay-callback", method = RequestMethod.POST, produces = "application/xml; charset=UTF-8")
    public @ResponseBody Response onWeapppayNotify(@RequestBody Map<String, String> requestParameters) {
    	
    	CallbackRequest callbackRequest = new WeapppayCallbackRequest(requestParameters);
        
    	CallbackResponse callbackResponse = new CallbackResponse();
    	
    	try {

    	    if(callbackRequest.isValid()) {
    	        
    	        // 0. extract pay_transaction from request
    	        PayTransaction payTransaction = callbackRequest.getPayTransaction();
    	        
    	        // 1. load payment_context by out_trade_no
                PaymentContext paymentContext =  paymentService.loadContext(payTransaction.getOutTradeNo());
                
                // 2. validate payment_context and callback_request, may throw business exception here
                paymentFacade.validate(paymentContext, callbackRequest);
                
                // 3. do paid process 
                callbackResponse = paymentFacade.paid(paymentContext, payTransaction);
    	        
    	    } else {
    	        
    	        callbackResponse.fail().message("支付参数有误");
    	        
    	    }
    	    
    	} catch (BusinessException e) {
    	    
    	    logger.error("#onWeapppayNotify - An business error occurs when doing callback process.", e);
    	    
    	    callbackResponse.fail().message(e.getMessage());
    	    
    	} catch (Exception e) {
    	    
    	    logger.error("@onWeapppayNotify - An exception error occurs when doing callback process.", e);
    	    
    	    callbackResponse.fail().message("支付回调失败");
    	}

        return callbackResponse.isValid() ? Response.newInstance().success() : Response.newInstance().fail(callbackResponse.getMessage());
    	
    }

}
